<script setup lang="ts">
import { ref } from 'vue';

import { useVbenModal, z } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  onlineDataSourceAddApi,
  onlineDataSourceEditApi,
  onlineDataSourceQueryByIdApi,
} from '#/api/onlineDesign/dataSource';
import { queryDictOptionsApi } from '#/utils';
import { asyncValidDataApi } from '#/utils/handle/async-rules';

const record = ref({});
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据源名称',
      },
      fieldName: 'dbName',
      label: '数据源名称',
      rules: z.string().max(30, '数据源名称最多30个字符'),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据源编码',
      },
      fieldName: 'dbCode',
      label: '数据源编码',
      dependencies: {
        triggerFields: ['dbCode'],
        // 实现异步API校验
        rules(values, formApi) {
          const rowId = formApi.values?.id;
          return asyncValidDataApi(
            z.string({ required_error: '请输入数据源编码' }),
            {
              tableName: 'online_data_source',
              fieldName: 'db_code',
              rowId,
              sqlSelect: `del_flag = 0`,
            },
          );
        },
      },
    },
    {
      component: 'ApiRadioGroup',
      defaultValue: 'MySql5.7+',
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: item.itemVal,
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'data_base_type',
        },
      },
      fieldName: 'dbType',
      label: '数据源类型',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入驱动类',
      },
      fieldName: 'dbDriver',
      label: '驱动类',
      rules: 'required',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入数据源地址',
      },
      fieldName: 'dbUrl',
      label: '数据源地址',
      rules: 'required',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入用户名',
      },
      fieldName: 'dbUsername',
      label: '用户名',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入密码',
      },
      fieldName: 'dbPassword',
      label: '密码',
      rules: 'required',
    },
    {
      component: 'ApiRadioGroup',
      defaultValue: 1,
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'yes_or_no',
        },
      },
      fieldName: 'isDefault',
      help: '如果存在多个使用中的数据源,则优先使用默认数据源',
      label: '是否默认',
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
      },
      fieldName: 'remark',
      label: '备注',
      formItemClass: 'col-span-2 items-baseline',
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  title: '数据源',
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = modalApi.getData<Record<string, any>>();
      modalApi.setState({
        title: `${record.value.id ? '编辑' : '新增'}数据源`,
      });
      if (record.value.id) {
        initFun();
      }
    }
  },
});

async function initFun() {
  const res = await onlineDataSourceQueryByIdApi({ id: record.value.id });
  await formApi.setValues(res, false);
}
async function onSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    if (record.value.id) {
      const msg = await onlineDataSourceEditApi(values);
      message.success(msg);
      await modalApi.close();
    } else {
      const msg = await onlineDataSourceAddApi(values);
      message.success(msg);
      await modalApi.close();
    }
  }
}
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
